﻿using Dapper;
using JX.Core;
using JX.Core.Entity;
using JX.Infrastructure;
using JX.Infrastructure.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JX.Application
{
	/// <summary>
	/// 用户有效期:为用户，用户组添加有效期并记录日志
	/// </summary>
	public class UserValidDateServiceAppDapper : IUserValidDateServiceAppDapper
	{
		private string m_FromUser = MyHttpContext.CurrentUserName;
		private string m_FromUserIp = Utility.GetClientIP();
		private readonly IUsersRepositoryDapper _usersRepository;
		private readonly IValidLogRepositoryDapper _validLogRepository;
		/// <summary>
		/// 仓储接口
		/// </summary>
		/// <param name="usersRepository"></param>
		/// <param name="validLogRepository"></param>
		public UserValidDateServiceAppDapper(IUsersRepositoryDapper usersRepository, IValidLogRepositoryDapper validLogRepository)
		{
			_usersRepository = usersRepository;
			_validLogRepository = validLogRepository;
		}

		/// <summary>
		/// 为所有会员增加
		/// </summary>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public bool IncreaseForAll(int howMany, string reason,string memo)
		{
			var userList = _usersRepository.GetList(writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}
		/// <summary>
		/// 为所有会员增加
		/// </summary>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public async Task<bool> IncreaseForAllAsync(int howMany, string reason, string memo)
		{
			var userList = await _usersRepository.GetListAsync(writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}

		/// <summary>
		/// 为指定的会员组增加
		/// </summary>
		/// <param name="groups">会员组ID集合</param>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public bool IncreaseForGroup(string groups, int howMany, string reason, string memo)
		{
			if (!DataValidator.IsValidId(groups))
			{
				return false;
			}
			string strWhere = "GroupId in @ids";
			var parameters = new DynamicParameters();
			parameters.Add("ids", StringHelper.GetArrayBySplit<int>(groups).ToArray());
			var userList = _usersRepository.GetList(strWhere, parameters,writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}
		/// <summary>
		/// 为指定的会员组增加
		/// </summary>
		/// <param name="groups">会员组ID集合</param>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public async Task<bool> IncreaseForGroupAsync(string groups, int howMany, string reason, string memo)
		{
			if (!DataValidator.IsValidId(groups))
			{
				return false;
			}
			string strWhere = "GroupId in @ids";
			var parameters = new DynamicParameters();
			parameters.Add("ids", StringHelper.GetArrayBySplit<int>(groups).ToArray());
			var userList = await _usersRepository.GetListAsync(strWhere, parameters, writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}

		/// <summary>
		/// 为指定的会员名增加
		/// </summary>
		/// <param name="toUser">会员名集合</param>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public bool IncreaseForUsers(string toUser, int howMany, string reason, string memo)
		{
			if (string.IsNullOrEmpty(toUser))
			{
				return false;
			}
			string strWhere = "UserName in @ids";
			var parameters = new DynamicParameters();
			parameters.Add("ids", StringHelper.GetArrayBySplit<string>(toUser).ToArray());
			var userList = _usersRepository.GetList(strWhere, parameters, writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}
		/// <summary>
		/// 为指定的会员名增加
		/// </summary>
		/// <param name="toUser">会员名集合</param>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public async Task<bool> IncreaseForUsersAsync(string toUser, int howMany, string reason, string memo)
		{
			if (string.IsNullOrEmpty(toUser))
			{
				return false;
			}
			string strWhere = "UserName in @ids";
			var parameters = new DynamicParameters();
			parameters.Add("ids", StringHelper.GetArrayBySplit<string>(toUser).ToArray());
			var userList = await _usersRepository.GetListAsync(strWhere, parameters, writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}

		/// <summary>
		/// 为指定的会员ID增加
		/// </summary>
		/// <param name="toUser">会员ID集合</param>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public bool IncreaseForUserID(string toUser, int howMany, string reason, string memo)
		{
			if (!DataValidator.IsValidId(toUser))
			{
				return false;
			}
			string strWhere = "UserID in @ids";
			var parameters = new DynamicParameters();
			parameters.Add("ids", StringHelper.GetArrayBySplit<int>(toUser).ToArray());
			var userList = _usersRepository.GetList(strWhere, parameters, writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}
		/// <summary>
		/// 为指定的会员ID增加
		/// </summary>
		/// <param name="toUser">会员ID集合</param>
		/// <param name="howMany">正数为增加的数量，负数为减少的数量</param>
		/// <param name="reason">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public async Task<bool> IncreaseForUserIDAsync(string toUser, int howMany, string reason, string memo)
		{
			if (!DataValidator.IsValidId(toUser))
			{
				return false;
			}
			string strWhere = "UserID in @ids";
			var parameters = new DynamicParameters();
			parameters.Add("ids", StringHelper.GetArrayBySplit<int>(toUser).ToArray());
			var userList = await _usersRepository.GetListAsync(strWhere, parameters, writeAndRead: WriteAndReadEnum.Write);
			foreach (var info in userList)
			{
				CheckDateAndUpdateUserEndTime(howMany, info);
				AddLog(howMany, info, reason, memo);
			}
			return true;
		}

		/// <summary>
		/// 检查日期并更新有效期
		/// </summary>
		/// <param name="date"></param>
		/// <param name="userInfo"></param>
		private void CheckDateAndUpdateUserEndTime(int date, UsersEntity userInfo)
		{
			if (date >= 9999)
			{
				userInfo.EndTime = new DateTime?(DateTime.MaxValue);
				_usersRepository.Update(userInfo);
			}
			else if (date <= -9999)
			{
				userInfo.EndTime = null;
				_usersRepository.Update(userInfo);
			}
			else
			{
				if (!userInfo.EndTime.HasValue || (userInfo.EndTime.Value.CompareTo(DateTime.Now) <= 0))
				{
					if (date <= 0)
					{
						return;
					}
					userInfo.EndTime = new DateTime?(DateTime.Now.AddDays(date));
				}
				else
				{
					TimeSpan span = (TimeSpan)(DateTime.MaxValue - userInfo.EndTime.Value);
					//如果有效期超过日期时间最大值则不操作
					if ((span.TotalDays - date) > 0.0)
					{
						userInfo.EndTime = new DateTime?(userInfo.EndTime.Value.AddDays(date));
					}
				}
				_usersRepository.Update(userInfo);
			}
		}
		/// <summary>
		/// 添加日志
		/// </summary>
		/// <param name="money"></param>
		/// <param name="userInfo"></param>
		/// <param name="reason"></param>
		/// <param name="memo"></param>
		private void AddLog(int money, UsersEntity userInfo, string reason, string memo)
		{
			var logEntity = new ValidLogEntity();
			logEntity.UserName = userInfo.UserName;
			logEntity.ValidNum = Math.Abs(money);
			if (money > 0)
			{
				logEntity.IncomePayout = 1;
			}
			else
			{
				logEntity.IncomePayout = 2;
			}
			logEntity.Inputer = string.IsNullOrEmpty(m_FromUser) ? "System" : m_FromUser;
			logEntity.IP = m_FromUserIp;
			logEntity.LogTime = DateTime.Now;
			logEntity.Remark = reason;
			logEntity.Memo = memo;
			_validLogRepository.Add(logEntity);
		}

	}
}
